/**
 * @file 数据看板页面
 * @date 2025/11/21 10:11:30
 * @author lyqjob@yeah.net
 */

import React, { useState, useEffect } from 'react';
import { Card, Flex, Col, Row, Statistic, Typography, Select, DatePicker, Spin, Empty } from 'antd';
import { UserOutlined, EyeOutlined, CloudOutlined, ClockCircleOutlined, AreaChartOutlined, BarChartOutlined, PieChartOutlined } from '@ant-design/icons';
import LineChart from '@/components/Charts/Line';
import BarChart from '@/components/Charts/Bar';
import AreaChart from '@/components/Charts/Area';
import PieChart from '@/components/Charts/Pie';
import { Pie } from '@ant-design/plots';
import { adminApi } from '../../services/admin';
// 导入PieChart组件用于用户分布图表，导入Pie组件用于在线率图表

import './index.css';

const { Title, Text } = Typography;
const { Option } = Select;
const { RangePicker } = DatePicker;

// 统计卡片组件
const StatCard = ({ icon, title, value, color = '#1890ff', trend = null, description = '' }) => (
  <Card 
    hoverable 
    style={{ height: '100%', borderTop: `4px solid ${color}` }}
    className="stat-card"
  >
    <Row gutter={[16, 8]} align="middle">
      <Col span={4}>
        <div style={{ fontSize: '28px', color }}>
          {icon}
        </div>
      </Col>
      <Col span={16}>
        <Text type="secondary" style={{ fontSize: '14px' }}>{title}</Text>
        <div style={{ marginTop: '8px' }}>
          <Statistic 
            value={value} 
            valueStyle={{ fontSize: '24px', fontWeight: 'bold' }}
          />
        </div>
        {description && <Text type="secondary" style={{ fontSize: '12px', marginTop: '4px', display: 'block' }}>{description}</Text>}
      </Col>
      {trend && (
        <Col span={4} align="right">
          <Text style={{ color: trend.color, fontSize: '14px', fontWeight: 'bold' }}>
            {trend.value}
          </Text>
        </Col>
      )}
    </Row>
  </Card>
);

  const Dashboard = () => {
  const [loading, setLoading] = useState(true);
  const [dateRange, setDateRange] = useState(null);
  const [timeRange, setTimeRange] = useState('week'); // week, month, year
  const [stats, setStats] = useState({
    totalUsers: 1258,
    onlineUsers: 368,
    totalVisits: 8942,
    avgDuration: '6m 25s'
  });

  // 自定义在线率饼图组件
  const CustomOnlineRateChart = () => {
    // 安全地获取数据，使用stats中的在线用户和总用户数
    const onlineUsers = stats?.onlineUsers || 75;
    const totalUsers = stats?.totalUsers || 100;
    const offlineUsers = totalUsers - onlineUsers;
    
    // 准备饼图数据
    const data = [
      {
        type: '在线',
        value: onlineUsers
      },
      {
        type: '离线',
        value: Math.max(0, offlineUsers) // 确保不会出现负数
      }
    ];
    
    // 饼图配置
    const config = {
      data,
      angleField: 'value',
      colorField: 'type',
      radius: 0.8,
      innerRadius: 0.6,
      color: ['#52c41a', '#f5f5f5'], // 绿色表示在线，灰色表示离线
      label: {
        position: 'outside',
        formatter: (datum) => {
          if (!datum) return '';
          return `${datum.type || ''}: ${datum.value || 0}`;
        },
      },
      tooltip: {
        formatter: (datum) => {
          if (!datum) return { name: '', value: '' };
          const value = datum.value || 0;
          return {
            name: datum.type || '',
            value: `${value} (${((value / totalUsers) * 100).toFixed(1)}%)`,
          };
        },
      }
    };
    
    return (
      <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ width: '80%', height: '80%' }}>
          <Pie {...config} />
          {/* 显示在线率百分比 */}
          <div style={{ 
            position: 'absolute', 
            top: '50%', 
            left: '50%', 
            transform: 'translate(-50%, -50%)', 
            textAlign: 'center' 
          }}>
            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#52c41a' }}>
              {((onlineUsers / totalUsers) * 100).toFixed(1)}%
            </div>
            <div style={{ fontSize: '14px', color: '#666' }}>在线率</div>
          </div>
        </div>
      </div>
    );
  };

  // 模拟数据加载
  useEffect(() => {
    const timer = setTimeout(() => {
      setLoading(false);
    }, 1000);
    return () => clearTimeout(timer);
  }, []);


  useEffect(() => {
    getStatistics()
  }, [])

  // 获取数据
  const getStatistics = async () => {
    const [err,res] =await adminApi.getStatistics({timeRange:'week',startDate:'2025-01-01',endDate:'2026-01-07'})
    if(err){
      return
    }
    console.log(res)
    // setStats(res)
  }
  

  // 访问趋势数据（按时间范围）
  const getVisitTrendData = () => {
    if (timeRange === 'week') {
      return [
        { date: '周一', value: 120, type: '访问量' },
        { date: '周二', value: 182, type: '访问量' },
        { date: '周三', value: 191, type: '访问量' },
        { date: '周四', value: 234, type: '访问量' },
        { date: '周五', value: 290, type: '访问量' },
        { date: '周六', value: 330, type: '访问量' },
        { date: '周日', value: 310, type: '访问量' },
        { date: '周一', value: 90, type: '用户数' },
        { date: '周二', value: 130, type: '用户数' },
        { date: '周三', value: 150, type: '用户数' },
        { date: '周四', value: 180, type: '用户数' },
        { date: '周五', value: 200, type: '用户数' },
        { date: '周六', value: 230, type: '用户数' },
        { date: '周日', value: 210, type: '用户数' },
      ];
    } else if (timeRange === 'month') {
      return [
        { date: '第1周', value: 890, type: '访问量' },
        { date: '第2周', value: 1200, type: '访问量' },
        { date: '第3周', value: 1500, type: '访问量' },
        { date: '第4周', value: 1350, type: '访问量' },
        { date: '第1周', value: 580, type: '用户数' },
        { date: '第2周', value: 750, type: '用户数' },
        { date: '第3周', value: 920, type: '用户数' },
        { date: '第4周', value: 850, type: '用户数' },
      ];
    } else {
      // year
      return [
        { date: '1月', value: 3500, type: '访问量' },
        { date: '2月', value: 3800, type: '访问量' },
        { date: '3月', value: 4200, type: '访问量' },
        { date: '4月', value: 4500, type: '访问量' },
        { date: '5月', value: 4800, type: '访问量' },
        { date: '6月', value: 5200, type: '访问量' },
        { date: '7月', value: 5500, type: '访问量' },
        { date: '8月', value: 5800, type: '访问量' },
        { date: '9月', value: 6200, type: '访问量' },
        { date: '10月', value: 6500, type: '访问量' },
        { date: '11月', value: 6800, type: '访问量' },
        { date: '12月', value: 7200, type: '访问量' },
        { date: '1月', value: 2200, type: '用户数' },
        { date: '2月', value: 2500, type: '用户数' },
        { date: '3月', value: 2800, type: '用户数' },
        { date: '4月', value: 3100, type: '用户数' },
        { date: '5月', value: 3400, type: '用户数' },
        { date: '6月', value: 3700, type: '用户数' },
        { date: '7月', value: 4000, type: '用户数' },
        { date: '8月', value: 4300, type: '用户数' },
        { date: '9月', value: 4600, type: '用户数' },
        { date: '10月', value: 4900, type: '用户数' },
        { date: '11月', value: 5200, type: '用户数' },
        { date: '12月', value: 5500, type: '用户数' },
      ];
    }
  };

  // 用户分布数据
  const userDistributionData = [
    { type: '移动端', value: 62 },
    { type: '桌面端', value: 32 },
    { type: '平板', value: 6 }
  ];

  // 页面访问统计
  const pageStatsData = [
    { category: '首页', value: 3200, type: 'PV' },
    { category: '产品', value: 2800, type: 'PV' },
    { category: '资讯', value: 2400, type: 'PV' },
    { category: '用户', value: 1800, type: 'PV' },
    { category: '设置', value: 1200, type: 'PV' },
    { category: '首页', value: 1600, type: 'UV' },
    { category: '产品', value: 1400, type: 'UV' },
    { category: '资讯', value: 1200, type: 'UV' },
    { category: '用户', value: 900, type: 'UV' },
    { category: '设置', value: 600, type: 'UV' },
  ];

  // 累计用户趋势
  const growthData = [
    { date: '1月', value: 1000 },
    { date: '2月', value: 1500 },
    { date: '3月', value: 2200 },
    { date: '4月', value: 2800 },
    { date: '5月', value: 3500 },
    { date: '6月', value: 4200 },
    { date: '7月', value: 4800 },
    { date: '8月', value: 5500 },
    { date: '9月', value: 6200 },
    { date: '10月', value: 7000 },
    { date: '11月', value: 7800 },
    { date: '12月', value: 8500 },
  ];

  return (
    <div className="dashboard_container">
      {/* 页面标题和筛选器 */}
      <Row gutter={[16, 16]} className="header-section" align="middle">
        <Col flex="auto">
          <Title level={3} style={{ margin: 0 }}>数据看板</Title>
          <Text type="secondary">实时监控系统数据和用户行为</Text>
        </Col>
        <Col className="filter-section">
              <Row gutter={[16, 0]} align="middle">
            <Col>
              <Text style={{ marginRight: '8px' }}>时间范围:</Text>
            </Col>
            <Col>
              <Select 
                value={timeRange} 
                onChange={setTimeRange}
                style={{ width: 120 }}
              >
                <Option value="week">最近一周</Option>
                <Option value="month">最近一月</Option>
                <Option value="year">最近一年</Option>
              </Select>
            </Col>
            <Col>
              <RangePicker 
                onChange={(dates) => setDateRange(dates)}
                style={{ width: 320 }}
              />
            </Col>
          </Row>
        </Col>
      </Row>

      {loading ? (
        <div className="loading-container">
          <Spin size="large" />
        </div>
      ) : (
        <>
          {/* 统计卡片区域 */}
          <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
            <Col xs={24} sm={12} md={6}>
              <StatCard 
                icon={<UserOutlined />} 
                title="总用户数" 
                value={stats.totalUsers} 
                color="#1890ff" 
                trend={{ value: '+12%', color: '#52c41a' }}
                description="相比上月"
              />
            </Col>
            <Col xs={24} sm={12} md={6}>
              <StatCard 
                icon={<CloudOutlined />} 
                title="在线用户数" 
                value={stats.onlineUsers} 
                color="#52c41a"
                trend={{ value: '+8%', color: '#52c41a' }}
                description="相比昨日同时段"
              />
            </Col>
            <Col xs={24} sm={12} md={6}>
              <StatCard 
                icon={<EyeOutlined />} 
                title="总访问量" 
                value={stats.totalVisits} 
                color="#faad14"
                trend={{ value: '+23%', color: '#52c41a' }}
                description="今日总访问"
              />
            </Col>
            <Col xs={24} sm={12} md={6}>
              <StatCard 
                icon={<ClockCircleOutlined />} 
                title="平均访问时长" 
                value={stats.avgDuration} 
                color="#f5222d"
                trend={{ value: '+36s', color: '#52c41a' }}
                description="平均停留时间"
              />
            </Col>
          </Row>

          {/* 主要图表区域 */}
          <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
            <Col xs={24} lg={16}>
              <Card 
                title={
                  <Row gutter={[16, 0]} align="middle">
                    <Col><span className="chart-title"><AreaChartOutlined /> 访问趋势分析</span></Col>
                    <Col>
                      <Select 
                        value={timeRange} 
                        onChange={setTimeRange}
                        style={{ width: 120 }}
                        size="small"
                      >
                        <Option value="week">周视图</Option>
                        <Option value="month">月视图</Option>
                        <Option value="year">年视图</Option>
                      </Select>
                    </Col>
                  </Row>
                }
                className="chart-card"
                  styles={{ body: { padding: 0 } }}
                >
                <div className="chart-container">
                  <LineChart 
                    data={getVisitTrendData()} 
                    config={{
                      xField: 'date',
                      yField: 'value',
                      seriesField: 'type',
                      smooth: true,
                      animation: {
                        appear: {
                          animation: 'path-in',
                          duration: 1000,
                        },
                      },
                      interactions: [
                        {
                          type: 'active-region',
                          enable: false,
                        },
                        {
                          type: 'element-active',
                        },
                      ],
                      yAxis: {
                        label: {
                          formatter: (v) => `${v}`,
                        },
                      },
                    }}
                  />
                </div>
              </Card>
            </Col>
            <Col xs={24} lg={8}>
              <Card 
                title={<span className="chart-title"><PieChartOutlined /> 用户分布</span>} 
                className="chart-card"
                  styles={{ body: { padding: 0 } }}
                >
                <div className="chart-container">
                  <PieChart 
                    data={userDistributionData}
                    config={{
                      angleField: 'value',
                      colorField: 'type',
                      radius: 0.8,
                      label: {
                        position: 'outside',
                        content: '{name}: {percentage}',
                      },
                      interactions: [
                        {
                          type: 'pie-legend-active',
                        },
                        {
                          type: 'element-active',
                        },
                      ],
                    }}
                  />
                </div>
              </Card>
            </Col>
          </Row>

          {/* 次要图表区域 */}
          <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
            <Col xs={24} md={12}>
              <Card 
                title={<span className="chart-title"><BarChartOutlined /> 页面访问统计</span>} 
                className="chart-card"
                  styles={{ body: { padding: 0 } }}
                >
                <div className="chart-container">
                  <BarChart 
                    data={pageStatsData}
                    config={{
                      xField: 'category',
                      yField: 'value',
                      seriesField: 'type',
                      isGroup: true,
                      animation: {
                        appear: {
                          animation: 'path-in',
                          duration: 1000,
                        },
                      },
                    }}
                  />
                </div>
              </Card>
            </Col>
            <Col xs={24} md={12}>
              <Card 
                title={<span className="chart-title">用户增长率</span>} 
                className="chart-card"
                  styles={{ body: { padding: 0 } }}
                >
                <div className="chart-container">
                  <AreaChart 
                    data={growthData.map(item => ({ ...item, type: '累计用户' }))}
                    config={{
                      xField: 'date',
                      yField: 'value',
                      seriesField: 'type',
                      smooth: true,
                      areaStyle: {
                        fillOpacity: 0.3,
                      },
                    }}                  />
                </div>
              </Card>
            </Col>
            
          </Row>
          <Row>
            <Col xs={24} md={10}>
              <Card 
                title={<span className="chart-title">在线率</span>} 
                className="chart-card"
                  styles={{ body: { padding: 0 } }}
                >
                <div className="chart-container" style={{ height: '300px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  {/* 提供自定义组件以更好地控制饼图数据和样式 */}
                  <CustomOnlineRateChart />
                  {/* 使用自定义组件展示在线率饼图 */}
                </div>
              </Card>
            </Col>
          </Row>
        </>
      )}
    </div>
  );
};

export default Dashboard;
